package com.t2t.top.ha;

import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;

public class RedisHAHanddleSlave  implements Watcher, Runnable, DataMonitorListener,ServletContextListener{
	String znode;

	DataMonitor dm;

	ZooKeeper zk;

	String filename;
	public static void main(String[] args) {
		try {
			new RedisHAHanddleSlave("192.168.72.22:2181", "192.168.72.22","slave", "/usr/soft/modify_vip.sh" ).run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public RedisHAHanddleSlave() {
		super();
	}

	public RedisHAHanddleSlave(String hostPort,String localIP, String type, String filename) throws KeeperException, IOException, InterruptedException {
		this.filename = filename;
		zk = new ZooKeeper(hostPort, 300000, this);
		String znode = initZnode(localIP, type);
		dm = new DataMonitor(zk, znode, this,filename);
	}

	private String initZnode(String localIP, String type)
			throws KeeperException, InterruptedException {
		if(zk.exists("/zk", false) == null){
			zk.create("/zk", "redis".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode. PERSISTENT);
		}
		String znode = null;
		if("master".equals(type.toLowerCase())){
			if(zk.exists("/zk/master", false) == null){
				znode = zk.create("/zk/master",localIP.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode. PERSISTENT);
			}
			zk.setData("/zk", "master".getBytes(), -1);
			zk.setData("/zk/master", localIP.getBytes(), -1);
			znode = "/zk/master";
		}else{
			if(zk.exists("/zk/slave", false) == null){
				znode = zk.create("/zk/slave", localIP.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode. PERSISTENT);
			}
			zk.setData("/zk/slave", localIP.getBytes(), -1);
			znode = "/zk/slave";
		}
		return znode;
	}
	public void exists(byte[] data) {
//            try {
//                FileOutputStream fos = new FileOutputStream(filename);
//                fos.write(data);
//                fos.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
	}

	public void closing(int rc) {
		synchronized (this) {
			notify();
		}
	}

	public void run() {
		try {
			synchronized (this) {
				while (!dm.dead) {
					wait();
				}
			}
		} catch (InterruptedException e) {
		}
	}

	public void process(WatchedEvent event) {
		System.out.println("新连接或者断开从服务器客户端。。。");
		dm.process(event);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			new RedisHAHanddleSlave("192.168.72.22:2181", "192.168.72.22","slave", "/usr/soft/modify_vip.sh" ).run();
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
